package Admin

import (
	"git.oschina.net/liukexing/RbacManager/models/center"
	. "git.oschina.net/liukexing/RbacManager/models/lib"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strings"
)

type NestPreparer interface {
	NestPrepare()
}
type CommonController struct {
	beego.Controller
	nodes []orm.Params
}

func (r *CommonController) Prepare() {
	group := "Admin"
	contoller, action := r.GetControllerAndAction()
	//浏览器兼容性
	r.Data["Respond"] = r.GetSession("respond")
	r.Data["username"] = r.GetSession("username")
	r.Data["showsearch"] = true
	r.Data["SearchUrl"] = beego.URLFor(group + "." + contoller + "." + action)
	//模块数据库查询
	uid := r.GetSession("userid")
	id, err := center.CheckAction(contoller, action, group)
	if err == nil {
		a, err := center.GetAction(id)
		if err == nil && uid == nil && !a.Ispublc {
			p, err := center.GetAction(a.Pid)
			if err == nil {
				r.Redirect(beego.URLFor(p.Group+"."+p.Controller+"."+p.Action), 302)
			}
		}
		//页面模板加载公用部分
		r.Layout = "public/Layout_rbac.html"
		contoller = strings.ToLower(strings.Replace(contoller, "Controller", "", 1))
		path := group + "/" + contoller + "/{Section}/" + strings.ToLower(action) + ".html"
		r.TplName = strings.Replace(path, "{Section}", "Content", 1)
		r.LayoutSections = make(map[string]string)
		for _, str := range []string{"SideBar", "HtmlHead", "Scripts"} {
			r.LayoutSections[str] = strings.Replace(path, "{Section}", str, 1)
		}
		//页面自动生成
		if a.Actiontype == 2 {
			CreateHtmlFile(r.Layout, r.TplName, r.LayoutSections)
		}
		r.nodes, _ = center.AccessList(uid.(int64), 2) //center.GetNodelistByGroupid(2)
		//公共数据初始化
		//用户权限验证
		isaccess := false
		var firstmenu []orm.Params
		for _, node := range r.nodes {
			if node["Level"].(int64) == 1 {
				firstmenu = append(firstmenu, node)
			}
			if node["Name"].(string) == (a.Group + "." + a.Controller + "." + a.Action) {
				isaccess = true
			}
		}
		r.Data["MenuList"] = firstmenu
		if r.Ctx.Request.Method == "GET" {
			beego.ReadFromRequest(&r.Controller)
		}
		//后续控制器初始化
		if app, ok := r.AppController.(NestPreparer); ok && a.Actiontype == 2 {
			if isaccess {
				app.NestPrepare()
			} else {
				r.Redirect(beego.URLFor("controllers.RootController.NotAccess"), 302)
			}

		}
	} else {
		r.Redirect(beego.URLFor("controllers.RootController.Error"), 302)
	}
}
